<?php

/*
 *  携程开放平台 - API
 *  李沂君
 *  2023/02/17
 */

namespace app\admin\model;

use think\Config;
use think\Model;
use liyijun\RedisPackage;


class Ctrip extends Model
{
    static private $api = [
        'dev'=>[
            'get_token_url'=>'http://openservice.open.uat.ctripqa.com/openserviceauth/authorize.ashx',//获取授权,参数 AID(联盟ID)、SID(站点ID)、KEY(安全码)
            'refresh_token_url'=>'http://openservice.open.uat.ctripqa.com/OpenServiceAuth/refresh.ashx',//更新TOKEN，参数 AID、SID、refresh_token（通过授权获取接口获得）
            'proxy'=>'http://openservice.open.uat.ctripqa.com/openservice/serviceproxy.ashx?AID=162&SID=375',//端口代理 AID、SID、ICODE、token、UUID(自己生成)、E（默认R3）、Mode(Format参数默认1)、Format（返回格式 JSON或XML,默认XML）
            'menpiaojingdianchaxun'=>'041f592e13f24c359e41da8acfc3178c',//门票景点查询(建议每日一次全量,5分钟一次增量)
            'menpiaojingdianxiangqing'=>'2ff54073468446bfa25e77d3051a2b59',//门票经典详情
            'menpiaoziyuanxiangqing'=>'0a8987905b814b179c415210dc0a82e6',//门票资源详情
            'menpiaodongtaibiaodan'=>'0db502255df140e8a2e8a66c4101a915',//门票动态表单
            'menpiaojiagerili'=>'d4afc4d925db48bbb0a4de9a3fdd8165',//门票价格日历
            'menpiaokedingxingjiancha'=>'2adb8f6326c1411eb9458e4fab4c5930',//门票可定性检查
            'menpiaochuangjiandingdan'=>'05c11efe4f07450ab3c55787f0ca9963',//门票创建订单
            'yonghuuidshengcheng'=>'e26bc561ac644aac9a806cfe883a7f33',//用户UID生成,用户需要开户,沃日
            'menpiaodingdanxinxichaxun'=>'39c75ec2b040426681b3595bfad1f786',//门票订单信息查询,
            'menpiaodingdanbianhua'=>'41711ae567b04d779a597cf2f4f5e732',//门票订单变化,一般5分钟调用一次，分销商可通过该接口获取订单状态及其他字段有变化的订单ID,若对数据及时性要求较高可每分钟调用一次
            'menpiaoketuijiancha'=>'d5ef8d48a49948c38717d47fca4e87ad',//门票可退检查[建议不做可退]
            'menpiaotuidan'=>'c97d60584a154f8a8e8841f038f721ce',//门票退单[建议不做可退]
            'huoqumenpiaopinzheng'=>'1ba847a2ac484d7c9f3ff31424576908',//获取门票凭证 (是否是二维码)
            'menpiaotuidingmingxi'=>'b324d133a0ca4ec2acb2f499d7a1a2f0',//门票退订明细
            'jingdiantupianjiekou'=>'1fc742c06bad4dd0bf9ad77cdda015ff',//景点图片接口,此接口不做本地
            'gaiqijiekou'=>'947f70f2b4b04e51bb20f9b4a1ee383a',//改期接口,不建议做改期,定错了直接联系客服退
            'gaizhengjiekou'=>'e4e8b7630c274a3783326fe2fe5bb009',//改正接口[×]
            'dingdankegairiqi'=>'d04413b9bde7422092366f9242a0b186',//获取订单可改日期接口
            'gaidanfeiyong'=>'2f086e49dbe34f4aa8c6d4a5e88dc32b',//获取改单费用接口
            'tijiaogaidan'=>'99c36ea760e14f2298360cedc19f4455',//提交改单接口
            'ziyuanquanliang'=>'2873cb4c9db549f7a99b30562a696aca',//资源全量接口，分销商通过该接口获取全量可售资源ID
            'yingxiaohuodong'=>'fd0854f45ad54826806b5ba15b92aa5a',//携程产品营销活动
        ],
        'product'=>[
            'get_token_url'=>'https://OpenServiceAuth.Ctrip.com/OpenServiceAuth/authorize.ashx',//获取授权,参数 AID(联盟ID)、SID(站点ID)、KEY(安全码)
            'refresh_token_url'=>'https://OpenServiceAuth.Ctrip.com/OpenServiceAuth/refresh.ashx',//更新TOKEN，参数 AID、SID、refresh_token（通过授权获取接口获得）
            'proxy'=>'https://sopenservice.ctrip.com/OpenService/ServiceProxy.ashx?AID=3800864&SID=21130124',//端口代理 AID、SID、ICODE、token、UUID(自己生成)、E（默认R3）、Mode(Format参数默认1)、Format（返回格式 JSON或XML,默认XML）
            'menpiaojingdianchaxun'=>'3e756f999d0a419eac8ed257e9a4cf5b',//门票景点查询(建议每日一次全量,5分钟一次增量)
            'menpiaojingdianxiangqing'=>'07310f189af1477aadcf8ca45f8171a4',//门票经典详情
            'menpiaoziyuanxiangqing'=>'9941a51c685a4fa289d3861c5dfbfad3',//门票资源详情
            'menpiaodongtaibiaodan'=>'5e77d1765fe7488085ae82037216d31e',//门票动态表单
            'menpiaojiagerili'=>'8a813070d06f4482be39ea1f349624c5',//门票价格日历
            'menpiaokedingxingjiancha'=>'eedc35f1ca1b4751b477496ac00b6f21',//门票可定性检查
            'menpiaochuangjiandingdan'=>'e342195619ba4ca98b642dd5b42dc8fb',//门票创建订单
            'yonghuuidshengcheng'=>'27f2055a974841da8f771a4a0ddbf4d3',//用户UID生成,用户需要开户,沃日
            'menpiaodingdanxinxichaxun'=>'503e93cef33a4c3caa3cb46621a7fa32',//门票订单信息查询,
            'menpiaodingdanbianhua'=>'0c3edd6a6f934689a844fe911e21d226',//(可以不用  存入本地自行查询)门票订单变化,一般5分钟调用一次，分销商可通过该接口获取订单状态及其他字段有变化的订单ID,若对数据及时性要求较高可每分钟调用一次
            'menpiaoketuijiancha'=>'9ace498c96b8430bbaa7fd45a4ac4c8d',//门票可退检查[建议不做可退]
            'menpiaotuidan'=>'bcb9a8bed0bb446f8db39c3ea5ef817d',//门票退单[建议不做可退]
            'huoqumenpiaopinzheng'=>'44e141473ce94b96b7ce4136e619fda2',//获取门票凭证
            'menpiaotuidingmingxi'=>'7fd4cffe6b964b76944a65b8a4325819',//门票退订明细
            'jingdiantupianjiekou'=>'357ce531b48d489a8c4eaa71ec1194d7',//景点图片接口,此接口不做本地
            'gaiqijiekou'=>'d949d824174047248457ba4e4d5a19cf',//改期接口,不建议做改期,定错了直接联系客服退
            'gaizhengjiekou'=>'eb500a95f42d403d9f77dcb2941d5e59',//改正接口[×]
            'dingdankegairiqi'=>'d04413b9bde7422092366f9242a0b186',//获取订单可改日期接口
            'gaidanfeiyong'=>'2f086e49dbe34f4aa8c6d4a5e88dc32b',//获取改单费用接口
            'tijiaogaidan'=>'99c36ea760e14f2298360cedc19f4455',//提交改单接口
            'ziyuanquanliang'=>'2873cb4c9db549f7a99b30562a696aca',//资源全量接口，分销商通过该接口获取全量可售资源ID
            'yingxiaohuodong'=>'fd0854f45ad54826806b5ba15b92aa5a',//携程产品营销活动
        ]
    ];


    /**
     * 获取授权
     */
    static private function GetToken(){
//        $reids = new RedisPackage();
//        $access_token = $reids->get('ctrip_access_token');
//        if(empty($access_token)){
            $res = self::post(self::$api[Config::get('ctrip.env')]['get_token_url'],[
                'AID'=>Config::get('ctrip.aid'),
                'SID'=>Config::get('ctrip.sid'),
                'KEY'=>Config::get('ctrip.key')
            ]);
            $res = json_decode($res,true);
            return $res['Access_Token'];
//            if(array_key_exists('Access_Token',$res)){
//                $reids->set("ctrip_access_token",$res['Access_Token'],$res['Expires_In']-30);
//                $reids->set("ctrip_refresh_token",$res['Refresh_Token']);
//            }
//        }
    }


    /**
     * 代理请求
     * @param $api_name 接口名
     * @param array $params 参数数组
     */
    static public function send($api_name,$params=[]){
        $token = self::GetToken();
//        $redis = new RedisPackage();
        $params['AID'] = Config::get('ctrip.aid');
        $params['SID'] = Config::get('ctrip.sid');
        $params['ICODE'] = self::$api[Config::get('ctrip.env')][$api_name];
        $params['token'] =$token;
        $params['UUID'] =self::uuidcode();
        $params['Format'] = 'JSON';
        $params = json_encode($params);
        $res = self::http_post_json(self::$api[Config::get('ctrip.env')]['proxy'],$params);
        $res = json_decode($res,true);
//        print_r($res);exit;
//        if(array_key_exists('ErrCode',$res)&&$res['ErrCode']==232){
            //Token失效自动刷新Token并请求,测试环境每次token有效期都只有几分钟，目前暂时对失效的token做删除,让系统自己重新请求新token,如果正式环境token也只有几分钟的话，那么这里就要改成每次请求都自动刷新token，或者token不做保存,每次都请求新的token
//            $redis->Del('ctrip_access_token');
            //$token = self::refreshToken();
//            $params['token'] = $token;
//            self::send($api_name,$params);
//            echo '执行了这里';
            //return json_decode($response,true);
//        }
        return $res;
    }


    /**
     * 更新access_token
     */
    static private function refreshToken(){
        $redis = new RedisPackage();
        $res = self::post(self::$api[Config::get('ctrip.env')]['refresh_token_url'],[
            'AID'=>Config::get('ctrip.aid'),
            'SID'=>Config::get('ctrip.sid'),
            'refresh_token'=>$redis->get('ctrip_refresh_token')
        ]);
//        print_r($redis->get('ctrip_refresh_token'));
        $response = json_decode($res,true);
//        print_r($response);
        if(array_key_exists('Access_Token',$response)){
            $redis->set("ctrip_access_token",$response['Access_Token'],$response['Expires_In']);
            $redis->set("ctrip_refresh_token",$response['Refresh_Token']);

            return $response['Access_Token'];
        }else{
            return 0;
        }
    }


    /**
     * json 请求
     */
    static private function http_post_json($url, $jsonStr)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($jsonStr)
            )
        );
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $response;
    }


    /**
     * POST请求
     * @param $url 地址
     * @param $post 参数数组
     * @return bool|mixed
     */
    static private function post($url, $post){
        $ch = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POST, 1);//POST
        curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($post));//postData
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //success
        curl_setopt($ch, CURLOPT_HEADER,0);
        curl_setopt($ch, CURLINFO_HEADER_OUT,1);
        $sContent = curl_exec($ch);
        $aStatus = curl_getinfo($ch);
        //echo $strPOST;
        curl_close($ch);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }


    /**
     * 获取uuid
     */
    static function uuidcode(){
        $chars = md5(uniqid(mt_rand(), true));
        $uuid = substr ( $chars, 0, 8 ) . '-'
            . substr ( $chars, 8, 4 ) . '-'
            . substr ( $chars, 12, 4 ) . '-'
            . substr ( $chars, 16, 4 ) . '-'
            . substr ( $chars, 20, 12 );
        return $uuid ;
    }
}
